#include "cipher.h"

int calculateSHA256(const int fd, char *sha256_out)
{
    const EVP_MD *md = EVP_sha256();
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
    EVP_DigestInit_ex(ctx, md, NULL);

    ssize_t read_size;
    char buf[4096];
    memset(buf, 0, sizeof(buf));

    while ((read_size = read(fd, buf, sizeof(buf)) != 0))
    {
        EVP_DigestUpdate(ctx, buf, read_size);
    }

    unsigned char sha256[32];
    unsigned int sha256_size = sizeof(sha256);

    EVP_DigestFinal_ex(ctx, sha256, &sha256_size);

    for (int i = 0; i < 32; ++i)
    {
        char temp[3] = {0};
        sprintf(temp, "%02x", sha256[i]);
        strcat(sha256_out, temp);
    }

    EVP_MD_CTX_free(ctx);
    
    return 0;
}